﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using Microsoft.Office.Tools;
using System.Collections;
using LightingImportTool.Model;
using System.IO;
using Tools;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Xml;
using System.Web.Mail;
using LightingImportTool.Tools;
using LightingImportTool.Help;
using Microsoft.Office.Tools.Ribbon;
using LightingImportTool.Login;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Reflection;

namespace LightingImportTool
{
    public partial class CustomRibbon
    {
        private OpenFileDialog _openPitureDialog;

        private OpenFileDialog OpenPictureDialog
        {
            get
            {
                if (_openPitureDialog == null)
                {
                    _openPitureDialog = new OpenFileDialog();
                    _openPitureDialog.Title = "请选择导入的图片";
                    _openPitureDialog.Filter = "图片 (*.bmp;*.jpg;*.gif;*.png)|*.bmp;*.jpg;*.gif;*.png";
                    _openPitureDialog.RestoreDirectory = true;
                }
                return _openPitureDialog;
            }
        }

        private SaveFileDialog _exportPackageDialog;

        public SaveFileDialog ExportPackageDialog
        {
            get
            {
                if (_exportPackageDialog == null)
                {
                    _exportPackageDialog = new SaveFileDialog();
                    _exportPackageDialog.Title = "导出灯具包";
                    _exportPackageDialog.Filter = "灯具包 (*.zip;*.rar)|*.zip;*.rar";
                    _exportPackageDialog.RestoreDirectory = true;
                }
                return _exportPackageDialog;
            }
        }


        private OpenFileDialog _openPackageDialog;

        public OpenFileDialog OpenPackageDialog
        {
            get 
            {
                if (_openPackageDialog == null)
                {
                    _openPackageDialog = new OpenFileDialog();
                    _openPackageDialog.Title = "导入灯具包";
                    _openPackageDialog.Filter = "灯具包 (*.zip;*.rar)|*.zip;*.rar";
                    _openPackageDialog.RestoreDirectory = true;
                }
                return _openPackageDialog;
            }
        }
        
        private void CustomRibbon_Load(object sender, RibbonUIEventArgs e)
        {
            //this.BtnLogin.Click += BtnLogin_Click;
            //this.BtnCheck.Click += BtnCheck_Click;
            //this.BtnCommit.Click += BtnCommit_Click;
            //this.BtnHelp.Click += BtnHelp_Click;
            //this.BtnFeedback.Click += BtnFeedback_Click;
            //this.BtnAbout.Click += BtnAbout_Click;
        }

        private void BtnLogin_Click(object sender, RibbonControlEventArgs e)
        {
            LoginForm loginForm = new LoginForm();
            loginForm.ShowDialog();
        }

        private void BtnCheck_Click(object sender, RibbonControlEventArgs e)
        {
            new HelperWindow().ShowDialog();
        }

        private void BtnCommit_Click(object sender, RibbonControlEventArgs e)
        {
           
        }


        private void BtnHelp_Click(object sender, RibbonControlEventArgs e)
        {
            new HelperWindow().ShowDialog();
        }

        private void BtnFeedback_Click(object sender, RibbonControlEventArgs e)
        {
            ExceptionWindow window = new ExceptionWindow(new NotFiniteNumberException());
            window.ShowDialog();
        }

        private void BtnAbout_Click(object sender, RibbonControlEventArgs e)
        {
            new HelperWindow().ShowDialog();

        }

        private void BtnExportPackage_Click_1(object sender, RibbonControlEventArgs e)
        {
            if (ExportPackageDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    ExportPackageByZIP(ExportPackageDialog.FileName);
                }
                catch (Exception ex)
                {
                    ExceptionHandler.HandleException(ex);
                }
            }
        }

        private byte[] ExportPackageByZIP(string filePath)
        {
            byte[] fileBytes = null;

            using (Stream exportStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                List<CompressItem> zipList = new List<CompressItem>();

                // 压缩EXCEL文件
                Excel.Workbook workbook = Globals.ThisAddIn.Application.ActiveWorkbook;
                string fileName = string.Format("灯具信息{0}{1}", Globals.ThisAddIn.GetNowTimeString(), ".xlsx");
                string fullName = Path.Combine(Path.GetTempPath(), fileName);
                workbook.SaveCopyAs(fullName);

                using (Stream stream = File.OpenRead(fullName))
                {
                    zipList.Add(new CompressItem() { Name = fileName, Stream = SerializeHelper.ReadFully(stream) });
                    stream.Close();
                }

                try
                {
                    File.Delete(fullName);
                }
                catch (Exception ex)
                {
                    ExceptionHandler.HandleException(ex);
                }

                WorkbookModel workbookModel = Globals.ThisAddIn.GetActiveWorkbookModel();

                // 压缩图片
                foreach (ImageFile file in workbookModel.ImageFiles)
                {
                    zipList.Add(new CompressItem() { Name = file.Name, Stream = file.File });
                }

                // 压缩模型
                using (MemoryStream ms = new MemoryStream())
                {
                    StreamWriter writer = new StreamWriter(ms);
                    writer.Write(SerializeHelper.ConvertToJson(workbookModel.ImageModels));
                    writer.Flush();
                    zipList.Add(new CompressItem() { Name = "Relation.txt", Stream = SerializeHelper.ReadFully(ms) });
                    writer.Close();
                    ms.Close();
                }

                byte[] zip = ZipHelper.CreateZipFileStream(zipList);
                exportStream.Write(zip, 0, zip.Length);
                exportStream.Flush();
                exportStream.Close();
            }
            return fileBytes;
        }

        private void BtnOpenPackage_Click_1(object sender, RibbonControlEventArgs e)
        {
            if (OpenPackageDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            OpenPackage(OpenPackageDialog.FileName);
        }

        public void OpenPackage(string fileName)
        {
            try
            {
                WorkbookModel workbookModel = new WorkbookModel();
                string excelFile = null;
                foreach (CompressItem item in ZipHelper.UncompressZipFile(fileName))
                {
                    if(item.Name == "Relation.txt")
                    {
                        using(MemoryStream ms = new MemoryStream(item.Stream))
                        {
                            StreamReader reader = new StreamReader(ms);
                            string jsonText = reader.ReadToEnd();
                            List<ImageModel> modeList = SerializeHelper.ConvertFromJson<List<ImageModel>>(jsonText);
                            workbookModel.ImageModels.AddRange(modeList);
                            ms.Close();
                        }
                    }
                    else
                    {
                        if (Regex.IsMatch(item.Name, @"(xls|xlsx)$", RegexOptions.IgnoreCase))
                        {
                            excelFile = Path.Combine(Path.GetTempPath(), item.Name);
                            using (Stream stream = File.Open(excelFile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                            {
                                stream.Write(item.Stream, 0, item.Stream.Length);
                                stream.Flush();
                                stream.Close();
                            }
                        }
                        else if(Regex.IsMatch(item.Name, @"(bmp|jpg|gif|png)$", RegexOptions.IgnoreCase))
                        {
                            workbookModel.ImageFiles.Add(new ImageFile() { Name = item.Name, File = item.Stream });
                        }
                    }
                }

               Excel.Workbook workBook =  Globals.ThisAddIn.Application.Workbooks.Open(excelFile);
               Globals.ThisAddIn.WorkbookModels[workBook] = workbookModel;
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex);
            }

        }

        /// <summary>
        /// 插入图片
        /// </summary>
        /// <param name="fileInfo"></param>
        private void InsertPicture(FileInfo fileInfo)
        {
            try
            {
                string rangeKey = Globals.ThisAddIn.GetRangeKey();
                WorkbookModel workbookModel = Globals.ThisAddIn.GetActiveWorkbookModel();
                ImageModel imageModel = workbookModel.GetImageModel(rangeKey);

                Image image = null;
                if (imageModel != null)
                {
                    if (!MessageHelper.Confirm("当前单元格内原始的图片会被覆盖，是否继续？"))
                    {
                        return;
                    }

                    bool result = (from r in workbookModel.ImageModels
                                   where r != imageModel && r.Name == imageModel.Name
                                   select r).FirstOrDefault() != null;

                    ImageFile imageFile = imageFile = workbookModel.GetImageFile(imageModel.Name);
                    if (!result)
                    {
                        workbookModel.ImageFiles.Remove(imageFile);
                    }

                    Stream stream = null;
                    if ((stream = fileInfo.Open(FileMode.Open, FileAccess.Read)) != null)
                    {
                        using (stream)
                        {
                            byte[] bytes = SerializeHelper.ReadFully(stream);
                            image = SerializeHelper.ByteArrayToImage(bytes);
                            imageFile = new ImageFile() { Name = fileInfo.Name, File = bytes };
                            workbookModel.ImageFiles.Add(imageFile);
                            stream.Close();
                        }
                    }

                    imageModel.Name = fileInfo.Name;
                    imageModel.Length = fileInfo.Length;
                    imageModel.Width = image.Width;
                    imageModel.Height = image.Height;
                    imageModel.Format = fileInfo.Extension;
                }
                else
                {
                    ImageFile imageFile = workbookModel.GetImageFile(fileInfo.Name);
                    if (imageFile == null)
                    {
                        Stream stream = null;
                        if ((stream = fileInfo.Open(FileMode.Open, FileAccess.Read)) != null)
                        {
                            using (stream)
                            {
                                byte[] bytes = SerializeHelper.ReadFully(stream);
                                image = SerializeHelper.ByteArrayToImage(bytes);
                                imageFile = new ImageFile() { Name = fileInfo.Name, File = bytes };
                                workbookModel.ImageFiles.Add(imageFile);
                                stream.Close();
                            }
                        }

                        imageModel = new ImageModel();
                        imageModel.Key = rangeKey;
                        imageModel.Name = fileInfo.Name;
                        imageModel.Length = fileInfo.Length;
                        imageModel.Width = image.Width;
                        imageModel.Height = image.Height;
                        imageModel.Format = fileInfo.Extension;
                        workbookModel.ImageModels.Add(imageModel);
                    }
                    else
                    {
                        ImageModel firstModel = workbookModel.GetImageModelByName(fileInfo.Name);
                        imageModel = (ImageModel)firstModel.Clone();
                        imageModel.Key = rangeKey;
                        workbookModel.ImageModels.Add(imageModel);
                        image = SerializeHelper.ByteArrayToImage(imageFile.File);
                    }
                }

                if (image != null)
                {
                    Excel._Worksheet sheet = Globals.ThisAddIn.GetActiveWorkSheet();
                    Excel.Range ranges = Globals.ThisAddIn.Application.Selection;
                    Excel.Range firstRange = sheet.Cells.get_Item(ranges.Row, ranges.Column);

                    Clipboard.SetImage(ExcelHelper.GenThumbnail(image, (int)firstRange.Width - 3, (int)firstRange.Height -3));
                    Globals.ThisAddIn.GetActiveWorkSheet().Paste();

                    try
                    {
                        dynamic obj = Globals.ThisAddIn.Application.Selection.GetType().InvokeMember(
                            "ShapeRange", 
                            BindingFlags.Default | BindingFlags.GetProperty, 
                            null,
                            Globals.ThisAddIn.Application.Selection, 
                            null);
                        obj.IncrementLeft(3);
                        obj.IncrementTop(3);
                    }
                    catch (Exception e)
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex);
            }
        }

        private void PirtureImport_Click(object sender, RibbonControlEventArgs e)
        {
            if (OpenPictureDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            InsertPicture(new FileInfo(OpenPictureDialog.FileName));
        }

        private void PictureView_Click(object sender, RibbonControlEventArgs e)
        {
            string rangeKey = Globals.ThisAddIn.GetRangeKey();
            if (string.IsNullOrEmpty(rangeKey))
            {
                MessageHelper.ShowMessage("请选择单元格。");
                return;
            }

            WorkbookModel workbookModel = Globals.ThisAddIn.GetActiveWorkbookModel();
            ImageModel imageModel = workbookModel.GetImageModel(rangeKey);
            if (imageModel != null)
            {
                ImageFile imageFile = workbookModel.GetImageFile(imageModel.Name);
                ImageForm form = new ImageForm(imageModel, imageFile);
                form.ShowDialog();
            }
        }

        private void PictureDelete_Click(object sender, RibbonControlEventArgs e)
        {
            string rangeKey = Globals.ThisAddIn.GetRangeKey();
            if (string.IsNullOrEmpty(rangeKey))
            {
                MessageHelper.ShowMessage("请选择单元格。");
                return;
            }


            WorkbookModel workbookModel = Globals.ThisAddIn.GetActiveWorkbookModel();
            ImageModel imageModel = workbookModel.GetImageModel(rangeKey);
            if (imageModel != null)
            {
                if (MessageHelper.Confirm("是否单元格内导入的图片信息？"))
                {
                    bool hasOther = (from r in workbookModel.ImageModels
                                     where r != imageModel && r.Name == imageModel.Name
                                     select r).FirstOrDefault() != null;
                    if (!hasOther)
                    {
                        ImageFile imagefile = workbookModel.GetImageFile(imageModel.Name);
                        workbookModel.ImageFiles.Remove(imagefile);
                    }

                    workbookModel.ImageModels.Remove(imageModel);
                }
            }

        }


        private Timer _timer;

        private Timer Timer
        {
            get
            {
                if (_timer == null)
                {
                    _timer = new Timer();
                    _timer.Interval = 50000;
                    _timer.Tick += _timer_Tick;
                }
                return _timer;
            }
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            Timer.Stop();
            if (Timer.Tag != null)
            {
                string fileName = Timer.Tag.ToString();
                if (File.Exists(fileName))
                {
                    try
                    {
                        File.Delete(fileName);
                    }
                    catch (Exception ex)
                    {
                        ExceptionHandler.HandleException(ex);
                    }
                }
            }
        }


        private void BtnCommit_Click_1(object sender, RibbonControlEventArgs e)
        {
            string message = "是否将当前文档上传至服务器？";
            if (MessageHelper.Confirm(message))
            {
                try
                {

                    string tempFileName = Path.Combine(Path.GetTempPath(), "灯具信息" + Globals.ThisAddIn.GetNowTimeString() + ".zip");
                    byte[] bytes = ExportPackageByZIP(tempFileName);

                    Services.LightingService.Commit(bytes);
                    //MailMessage mailBox = EmailHelper.CreateMessage();
                    //mailBox.Subject = "灯具信息包";
                    //mailBox.Attachments.Add(new MailAttachment(tempFileName));
                    //EmailHelper.SendMessage(mailBox);
                    Timer.Tag = tempFileName;
                    Timer.Start();
                }
                catch (Exception ex)
                {
                    ExceptionHandler.HandleException(ex);
                }
            }
        }
    }
}
